package com.northpool.operator.dataset.index;

import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.common.database.DatabaseUtils;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.StpOperatorHelper;
import com.northpool.resources.datasource.IDataSource;
import com.northpool.resources.datatable.operate.ITableOperator;
import com.northpool.resources.datatable.operate.IndexBean;
import com.northpool.resources.datatable.operate.TableSchemaBean;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@OperatorInfo(
        ref = "TableDelPkOperator",
        version = "0.0.1",
        name = "删除索引",
        description = "数据表删除索引"
)
public class TableDelIndexOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "datasource", name = "数据源", desc = "数据源ID"),
            @InputParam(ref = "tableName", name = "表名称", desc = "数据表名称，如: tb_test"),
            @InputParam(ref = "field", name = "主键字段", desc = "需要创建的主键字段名称，如: kid"),
    })
    public TableDelIndexOperator() {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(TableDelIndexOperator.class,
                TestParamBuilder.aBuilder()
                        .param("datasource", "test_bcg")
                        .param("tableName", "bj_landuse")
                        .param("field", "code")
                        .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String datasource = paramTool.getStr("datasource");
        String dataSourceJson = DatabaseUtils.getDataSourceJson(datasource);
        String tableName = paramTool.getStr("tableName");
        String field = paramTool.getStr("field");
        IDataSource ds = IDataSource.fromJSON(dataSourceJson);
        ITableOperator tableOperator = ds.getTableOperator(tableName);
        TableSchemaBean tableSchemaBean = tableOperator.toTableSchemaBean();
        Map<String, IndexBean> indexMap = tableSchemaBean.getIndexMap();

        for (IndexBean value : indexMap.values()) {
            List<String> columns = value.getColnames();
            // 单个索引
            if (columns.contains(field) && columns.size() == 1) {
                tableOperator.dropIndex(value.getName()).get(60, TimeUnit.MINUTES);
                this.log("索引删除成功: {}", value.getName());
            }
        }
    }
}
